from department.models import Department, DepartmentRole, Work
from user.models import User
from pms.common.utils import flatten_view
from pms.common.views import PermissionDeny


def add_department_member(department, department_role, user, annotation=''):
    assert isinstance(department, Department)
    assert isinstance(department_role, DepartmentRole)
    assert isinstance(user, User)
    assert department_role.did == department  # 部门身份要部门控制部门
    work = Work(uid=user, rid=department_role, annotation=annotation)
    work.save()
    return work


def department_member_view(work):
    assert isinstance(work, Work)
    view = {
        'id': work.uid_id,
        'name': work.uid.name,
        'role': {
            'id': work.rid_id,
            'name': work.rid.name
        },
        'annotation': work.annotation
    }
    return view


def update_department_member(work, view):
    assert isinstance(work, Work)
    argv = flatten_view(view, {
        'rid_id': ['role', 'id'],
        'annotation': 'annotation'
    })
    if 'rid_id' in argv:  # 更改后的部门身份要和更改前的部门身份部门控制同一个部门
        assert DepartmentRole.objects.get(id=argv['rid_id']).did == work.rid.did
    work.__dict__.update(**argv)
    work.save()
    return work


def assert_member_of(user, department):
    """ 断言 user 是 department 的成员，并返回工作关系。否则抛出 PermissionDeny """
    try:
        return Work.objects.get(uid=user, rid__did=department)
    except Work.DoesNotExist:
        raise PermissionDeny
